package com.sharemarking.system.service;


import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import com.sharemarking.system.mapper.MemberMapper;
import com.sharemarking.system.mapper.MessageMapper;
import com.sharemarking.wa.common.entity.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author dxy
 */
@Service
public class JGPushService {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private JGPushConfig jgPushConfig;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private MessageMapper messageMapper;


//    public ResponseParams<?> pushAll() throws Exception {
//        String alert = request.getParameter("alert");
////        String title = request.getParameter("title");
//
//        pushAll(jgPushConfig.getJPushClient(), alert);
//        return ResponseParams.ok(null);
//    }


    public void pushTag(String messageStr, Integer memberId) {
        Message message = new Message();
        message.setTitle(messageStr);
        message.setMemberId(memberId);
        message.setCreateDate(new Date());
        message.setIsPushSms(0);
        messageMapper.insertMessage(message);

        String alias = memberMapper.getAlias(memberId);
        buildPushObject_android_tag_alertWithTitle(jgPushConfig.getJPushClient(), messageStr, alias);
    }




    public void pushAll(JPushClient jpushClient, String alert) {
        try {
            PushResult result = jpushClient.sendPush(PushPayload.alertAll(alert));
            // 请求结束后，调用 NettyHttpClient 中的 close 方法，否则进程不会退出。
            jpushClient.close();

        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
    }

    public void buildPushObject_android_tag_alertWithTitle(JPushClient jpushClient, String alert, String tag)  {
        try {
            if (tag == null){
                return;
            }
            PushResult result = jpushClient.sendPush(PushPayload.newBuilder()
                    .setPlatform(Platform.all())
                    .setAudience(Audience.alias(tag))
                    .setNotification(Notification.alert(alert))
                    .build());
        } catch (APIConnectionException e) {

        } catch (APIRequestException e) {

        }
        jpushClient.close();
    }


}
